package com.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class Test {
    public static void main(String[] args) {
//        test1();  // 783
        test2();  // 3249
//        test3();  // 127
    }

    // 普通程序员
    public static void test1() {
        Long start = System.currentTimeMillis();
        Long sum = 0L;
        for (Long i = 0L; i <= 10_0000_000; i++) {
            sum += i;
        }
        Long end = System.currentTimeMillis();

        System.out.println("sum = " + sum + " 时间 = " + (end - start));
    }

    // 会使用 ForkJoin
    public static void test2() {
        Long start = System.currentTimeMillis();
        Long sum = 0L;

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);  // 提交任务
        try {
            sum = submit.get();  // 获取计算结果
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        Long end = System.currentTimeMillis();
        System.out.println("sum = " + sum + " 时间 = " + (end - start));
    }

    // 使用 Stream并行流
    public static void test3() {
        Long start = System.currentTimeMillis();

        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);

        Long end = System.currentTimeMillis();
        System.out.println("sum = " + sum + " 时间 = " + (end - start));
    }
}
